<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="题目类型" prop="questionType">
        <el-select v-model="queryParams.questionType" placeholder="请选择题目类型" clearable>
          <el-option
            v-for="dict in questionTypeOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属章节" prop="chapterId">
        <el-tree-select
          v-model="queryParams.chapterId"
          :data="chapterOptions"
          :props="{ value: 'chapterId', label: 'chapterName', children: 'children' }"
          value-key="chapterId"
          placeholder="请选择所属章节"
          check-strictly
          clearable
        />
      </el-form-item>
      <el-form-item label="难度" prop="difficulty">
        <el-select v-model="queryParams.difficulty" placeholder="请选择难度" clearable>
          <el-option
            v-for="i in 5"
            :key="i"
            :label="getDifficultyLabel(i)"
            :value="i"
          >
            <el-rate
              :model-value="i"
              disabled
              show-score
              text-color="#ff9900"
              :texts="['简单', '较简单', '中等', '较难', '困难']"
            />
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:question:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:question:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:question:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="60">
        <template #default="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="题目类型" align="center" prop="questionType" width="100">
        <template #default="scope">
          <el-tag :type="getQuestionTypeTag(scope.row.questionType)">
            {{ getQuestionTypeLabel(scope.row.questionType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="题干内容" align="center" prop="questionContent" min-width="200">
        <template #default="scope">
          <el-popover
            placement="top-start"
            trigger="hover"
            :width="400"
          >
            <div v-html="renderMathContent(scope.row.questionContent)"></div>
            <template #reference>
              <div class="content-cell" v-html="renderMathContent(formatContent(scope.row.questionContent))"></div>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="所属章节" align="center" prop="chapterName" width="180">
        <template #default="scope">
          {{ getChapterName(scope.row.chapterId) }}
        </template>
      </el-table-column>
      <el-table-column label="难度" align="center" prop="difficulty" width="180">
        <template #default="scope">
          <el-rate
            v-model="scope.row.difficulty"
            disabled
            show-score
            text-color="#ff9900"
            :texts="['简单', '较简单', '中等', '较难', '困难']"
          />
        </template>
      </el-table-column>
      <el-table-column label="标准答案" align="center" prop="answer" min-width="150">
    <template #default="scope">
      <template v-if="scope.row.questionType === 3">
        <el-popover
          placement="top"
          trigger="hover"
          :width="300"
        >
    <template #default>
      <div v-if="scope.row.options">
        <div v-for="option in scope.row.options" :key="option.optionId" class="blank-answer-item">
          <strong>填空 {{ option.optionLabel }}：</strong>
          <span 
            :class="{ 'answer-hidden': !scope.row.showAnswer }"
            v-html="renderMathContent(option.optionContent?.split('|||').join(' 或 ') || '')"
          ></span>
        </div>
      </div>
    </template>
    <template #reference>
      <div 
        class="answer-cell" 
        :class="{ 'answer-hidden': !scope.row.showAnswer }"
        @click="toggleAnswer(scope.row)"
      >
        <el-tag size="small" type="info">共{{ scope.row.options?.length || 0 }}个填空</el-tag>
        <el-icon><View /></el-icon>
      </div>
    </template>
  </el-popover>
      </template>
      <template v-else-if="scope.row.questionType === 2">
      <div 
        class="answer-cell" 
        :class="{ 'answer-hidden': !scope.row.showAnswer }"
        @click="toggleAnswer(scope.row)"
      >
        {{ formatJudgeAnswer(scope.row.answer) }}
      </div>
    </template>
      <template v-else>
        <div 
          class="answer-cell" 
          :class="{ 'answer-hidden': !scope.row.showAnswer }"
          @click="toggleAnswer(scope.row)"
          v-html="renderMathContent(scope.row.answer)"
        ></div>
      </template>
    </template>
  </el-table-column>
      <el-table-column label="分值" align="center" prop="score" width="60">
        <template #default="scope">
          <span class="score-tag">{{ scope.row.score }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
            {{ scope.row.status === 0 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handlePreview(scope.row)">预览</el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:question:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:question:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
   <!-- 预览对话框 -->
   <el-dialog
      v-model="previewVisible"
      title="题目预览"
      width="600px"
      append-to-body
      @opened="renderMathInPreview" 
    >
      <div class="preview-container" ref="previewContainer">
        <!-- 题目类型 -->
        <div class="preview-type">
          <el-tag :type="getQuestionTypeTag(previewQuestion.questionType)">
            {{ getQuestionTypeLabel(previewQuestion.questionType) }}
          </el-tag>
          <span class="preview-difficulty">
            <el-rate
              v-model="previewQuestion.difficulty"
              disabled
              show-score
              text-color="#ff9900"
              :texts="['简单', '较简单', '中等', '较难', '困难']"
            />
          </span>
          <span class="preview-score">分值: {{ previewQuestion.score }}</span>
        </div>

        <!-- 题干 -->
        <div class="preview-title">题干:</div>
        <div class="preview-content content-html" v-html="previewQuestion.questionContent"></div>
        
        <!-- 选项 - 单选题/多选题 -->
        <template v-if="previewQuestion.questionType === 0 || previewQuestion.questionType === 1">
          <div class="preview-title">选项:</div>
          <div v-for="option in previewQuestion.options" :key="option.optionId" class="preview-option">
            <span class="option-label">{{ option.optionLabel }}.</span>
            <div class="preview-option-content content-html" v-html="option.optionContent"></div>
          </div>
        </template>

        <!-- 答案 -->
        <div class="preview-title">答案:</div>
        <!-- 单选题/多选题答案 -->
        <div v-if="previewQuestion.questionType === 0 || previewQuestion.questionType === 1" class="preview-answer">
          {{ previewQuestion.answer }}
        </div>
        <!-- 判断题答案 -->
        <div v-else-if="previewQuestion.questionType === 2" class="preview-answer">
          {{ formatJudgeAnswer(previewQuestion.answer) }}
        </div>
        <!-- 填空题答案 -->
        <div v-else-if="previewQuestion.questionType === 3">
          <div v-for="(option, index) in previewQuestion.options" :key="index" class="preview-blank">
            <div class="preview-blank-label">填空 {{ option.optionLabel }}:</div>
            <div class="preview-blank-answers">
              {{ option.optionContent?.split('|||').join(' 或 ') || '' }}
            </div>
          </div>
        </div>
        <!-- 简答题答案 -->
        <div v-else-if="previewQuestion.questionType === 4" class="preview-answer" v-html="previewQuestion.answer"></div>
        
        <!-- 解析 -->
        <div v-if="previewQuestion.analysis" class="preview-title">解析:</div>
        <div v-if="previewQuestion.analysis" class="preview-content content-html" v-html="previewQuestion.analysis"></div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup name="Question">
import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion } from "@/api/manage/question";
import { listChapter } from "@/api/manage/chapter";
import { View } from '@element-plus/icons-vue'
import { getCurrentInstance, ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import katex from 'katex';
import 'katex/dist/katex.min.css';
import { ElMessage } from 'element-plus';

const router = useRouter();
const { proxy } = getCurrentInstance();

// 题目列表数据
const questionList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 章节数据
const chapterOptions = ref([]);

// 预览相关
const previewVisible = ref(false);
const previewQuestion = ref({});
const previewContainer = ref(null);

// 题目类型选项
const questionTypeOptions = [
  { value: 0, label: '单选题' },
  { value: 1, label: '多选题' },
  { value: 2, label: '判断题' },
  { value: 3, label: '填空题' },
  { value: 4, label: '简答题' }
];

// 查询参数
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    questionType: null,
    chapterId: null,
    difficulty: null,
  }
});

const { queryParams } = toRefs(data);

// 添加数学公式渲染函数
function renderMathContent(content) {
  if (!content) return '';
  
  try {
    // 处理块级公式 $$...$$
    content = content.replace(/\$\$([\s\S]+?)\$\$/g, (match, formula) => {
      try {
        return katex.renderToString(formula, {
          displayMode: true,
          throwOnError: false
        });
      } catch (err) {
        console.error('KaTeX error:', err);
        return match;
      }
    });

    // 处理行内公式 $...$
    content = content.replace(/\$([^\$]+)\$/g, (match, formula) => {
      try {
        return katex.renderToString(formula, {
          displayMode: false,
          throwOnError: false
        });
      } catch (err) {
        console.error('KaTeX error:', err);
        return match;
      }
    });

    return content;
  } catch (err) {
    console.error('Content processing error:', err);
    return content;
  }
}

watch(
  () => router.currentRoute.value.path,
  () => {
    getList();
  }
);

/** 查询题目列表 */
function getList() {
  loading.value = true;
  listQuestion(queryParams.value).then(response => {
    questionList.value = response.rows.map(item => {
      // 如果是填空题，需要获取选项数据
      if (item.questionType === 3) {
        // 使用后端返回的选项数据
        const options = item.options || [];
        // 按照 optionLabel 排序 (A, B, C...)
        const sortedOptions = options.sort((a, b) => a.optionLabel.localeCompare(b.optionLabel));
        
        return {
          ...item,
          showAnswer: false,
          options: sortedOptions.map(opt => ({
            ...opt,
            // 处理答案中可能包含的分隔符
            optionContent: opt.optionContent || ''
          }))
        };
      }
      return {
        ...item,
        showAnswer: false
      };
    });
    
    total.value = response.total;
    loading.value = false;
  });
}

/** 获取章节树形数据 */
function getChapterTreeselect() {
  listChapter().then(response => {
    const data = { chapterId: 0, chapterName: '离散数学', children: [] };
    data.children = handleTree(response.data, "chapterId", "parentId");
    chapterOptions.value = [data];
  });
}

// 添加处理树形结构的方法
const handleTree = (data, id, parentId) => {
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: 'children'
  };

  const childrenListMap = {};
  const nodeIds = {};
  const tree = [];

  for (const d of data) {
    const parentId = d[config.parentId];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    nodeIds[d[config.id]] = d;
    childrenListMap[parentId].push(d);
  }

  for (const d of data) {
    const parentId = d[config.parentId];
    if (nodeIds[parentId] == null) {
      tree.push(d);
    }
  }

  for (const t of tree) {
    adaptToChildrenList(t);
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]];
    }
    if (o[config.childrenList]) {
      for (const c of o[config.childrenList]) {
        adaptToChildrenList(c);
      }
    }
  }
  return tree;
};

/** 获取章节名称 */
function getChapterName(chapterId) {
  const path = [];
  const findPath = (chapters, id) => {
    for (const chapter of chapters) {
      if (chapter.chapterId === id) {
        path.unshift(chapter.chapterName);
        return true;
      }
      if (chapter.children) {
        if (findPath(chapter.children, id)) {
          path.unshift(chapter.chapterName);
          return true;
        }
      }
    }
    return false;
  };
  
  findPath(chapterOptions.value, chapterId);
  return path.join(' / ');
}

/** 获取节点及其所有子节点的ID */
function getAllChildrenIds(chapterId) {
  const ids = new Set();
  
  const collectIds = (chapters, targetId) => {
    for (const chapter of chapters) {
      if (chapter.chapterId === targetId) {
        // 转换为数字类型
        ids.add(Number(chapter.chapterId));
        if (chapter.children) {
          collectChildrenIds(chapter);
        }
        return true;
      }
      if (chapter.children && collectIds(chapter.children, targetId)) {
        return true;
      }
    }
    return false;
  };

  const collectChildrenIds = (chapter) => {
    // 转换为数字类型
    ids.add(Number(chapter.chapterId));
    if (chapter.children) {
      chapter.children.forEach(child => collectChildrenIds(child));
    }
  };

  collectIds(chapterOptions.value, chapterId);
  return Array.from(ids);
}
/** 获取题目类型标签 */
function getQuestionTypeLabel(type) {
  const option = questionTypeOptions.find(opt => opt.value === type);
  return option ? option.label : '';
}

/** 获取题目类型标签样式 */
function getQuestionTypeTag(type) {
  const types = ['success', 'warning', 'info', 'danger', 'primary'];
  return types[type] || 'default';
}

/** 获取难度标签 */
function getDifficultyLabel(level) {
  const labels = ['简单', '较简单', '中等', '较难', '困难'];
  return labels[level - 1] || '';
}

/** 格式化内容 - 新版本支持同时显示文本和图片 */
function formatContent(content) {
  if (!content) return '';
  
  // 创建临时DOM元素解析内容
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = content;
  
  // 查找图片元素
  const images = tempDiv.querySelectorAll('img');
  let hasImage = images.length > 0;
  
  // 获取纯文本内容（用于显示文字部分）
  let textContent = tempDiv.textContent || '';
  textContent = textContent.trim();
  
  // 截断文本，保留前30个字符
  let truncatedText = textContent.length > 30 ? textContent.substring(0, 30) + '...' : textContent;
  
  // 如果有图片，创建带图片的预览
  if (hasImage) {
    // 只保留第一张图片作为缩略图
    const firstImage = images[0];
    
    // 设置图片缩略图样式
    firstImage.style.maxWidth = '100%';
    firstImage.style.maxHeight = '40px';
    firstImage.style.objectFit = 'contain';
    firstImage.style.display = 'block';
    firstImage.style.margin = '5px auto';
    
    // 返回文本+图片组合或仅图片（如果没有文字）
    if (truncatedText) {
      return `<div>${truncatedText}</div><div class="thumbnail-preview">${firstImage.outerHTML}</div>`;
    } else {
      return `<div class="thumbnail-preview">${firstImage.outerHTML}</div>`;
    }
  }
  
  // 没有图片，只返回文本
  return truncatedText;
}

/** 切换答案显示状态 */
function toggleAnswer(row) {
  row.showAnswer = !row.showAnswer;
}

/** 搜索按钮操作 */
function handleQuery() {
  let params = { ...queryParams.value };
  
  if (params.chapterId) {
    // 如果选择了离散数学（章节ID为0），则显示所有题目，不添加章节ID过滤
    if (params.chapterId === 0) {
      // 删除 chapterId，不作为查询条件
      delete params.chapterId;
    } else {
      // 获取选中节点及其所有子节点的ID
      const chapterIds = getAllChildrenIds(params.chapterId);
      params = {
        ...params,
        chapterIds: chapterIds
      };
    }
  }
  
  loading.value = true;
  listQuestion(params).then(response => {
    questionList.value = response.rows.map(item => {
      // 如果是填空题，需要获取选项数据
      if (item.questionType === 3) {
        // 从题目内容中计算填空数量
        const blankCount = (item.questionContent.match(/_{8}/g) || []).length;
        
        // 获取填空答案
        const answers = item.answer ? item.answer.split(',') : [];
        
        // 生成填空选项
        const options = Array.from({ length: blankCount }, (_, index) => ({
          optionId: `blank_${index}`,
          optionLabel: String.fromCharCode(65 + index),
          // 使用对应的答案，如果没有则为空字符串
          optionContent: answers[index] || ''
        }));
        
        return {
          ...item,
          showAnswer: false,
          options: options
        };
      }
      return {
        ...item,
        showAnswer: false
      };
    });
    total.value = response.total;
    loading.value = false;
  });
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.questionId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 预览按钮操作 - 修改后的版本 */
function handlePreview(row) {
  loading.value = true;
  // 直接从后端获取完整的题目数据，确保有选项
  getQuestion(row.questionId).then(response => {
    loading.value = false;
    // 处理获取到的数据
    let questionData = response.data;
    
    // 如果是填空题，要确保选项数据正确排序
    if (questionData.questionType === 3 && questionData.options) {
      questionData.options = questionData.options.sort((a, b) => 
        a.optionLabel.localeCompare(b.optionLabel)
      );
    }
    
    // 确保选项排序正确 (单选题和多选题)
    if ((questionData.questionType === 0 || questionData.questionType === 1) && questionData.options) {
      questionData.options = questionData.options.sort((a, b) => 
        a.optionLabel.localeCompare(b.optionLabel)
      );
    }
    
    // 更新预览数据并显示对话框
    previewQuestion.value = questionData;
    previewVisible.value = true;
  }).catch(error => {
    loading.value = false;
    console.error('获取题目详情失败', error);
    ElMessage.error('获取题目详情失败');
  });
}

/** 修改MathJax加载方式 */
const loadMathJax = () => {
  return new Promise((resolve) => {
    if (window.MathJax) {
      // 如果已经加载，重新配置并尝试渲染
      try {
        if (window.MathJax.typesetPromise) {
          window.MathJax.typesetPromise();
        } else if (window.MathJax.typeset) {
          window.MathJax.typeset();
        }
      } catch (e) {
        console.error('MathJax已加载但渲染失败:', e);
      }
      resolve(window.MathJax);
      return;
    }
    
    // 先创建配置
    window.MathJax = {
      tex: {
        inlineMath: [['$', '$'], ['\\(', '\\)']],
        displayMath: [['$$', '$$'], ['\\[', '\\]']]
      },
      svg: {
        fontCache: 'global'
      },
      startup: {
        ready: () => {
          console.log('MathJax is ready');
          window.MathJax.startup.defaultReady();
          resolve(window.MathJax);
        }
      }
    };
    
    // 然后加载脚本
    const script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
    script.async = true;
    script.onload = () => {
      console.log('MathJax脚本已加载');
    };
    script.onerror = (e) => {
      console.error('MathJax加载失败:', e);
    };
    document.head.appendChild(script);
  });
};

/** 优化渲染函数，添加更多日志和重试机制 */
const renderMathInPreview = async () => {
  console.log('开始渲染公式');
  await nextTick();
  
  try {
    const mathJax = await loadMathJax();
    console.log('MathJax已加载', mathJax);
    
    // 确保内容已经渲染到DOM
    await nextTick();
    
    // 尝试多种方法渲染公式
    if (previewContainer.value) {
      if (mathJax.typesetPromise) {
        await mathJax.typesetPromise([previewContainer.value]);
        console.log('使用typesetPromise方法渲染完成');
      } else if (mathJax.typeset) {
        mathJax.typeset([previewContainer.value]);
        console.log('使用typeset方法渲染完成');
      } else {
        console.error('找不到MathJax的渲染方法');
      }
    } else {
      console.error('找不到预览容器');
    }
  } catch (error) {
    console.error('MathJax渲染错误:', error);
    
    // 备选方案：使用KaTeX
    try {
      if (previewContainer.value) {
        // 找到所有包含数学公式的元素
        const elements = previewContainer.value.querySelectorAll('.content-html, .preview-option-content, .preview-blank-answers');
        elements.forEach(el => {
          const html = el.innerHTML;
          if (html && (html.includes('$') || html.includes('\\('))) {
            // 重新渲染数学公式
            el.innerHTML = renderMathContent(html);
          }
        });
      }
    } catch (katexError) {
      console.error('KaTeX渲染备选方案也失败:', katexError);
    }
  }
};

/** 修改按钮操作 */
function handleUpdate(row) {
  const questionId = row.questionId || ids.value[0];
  const questionType = row.questionType || questionList.value.find(item => item.questionId === questionId)?.questionType;
  
  if (questionType === 0) {
    router.push(`/question/single/edit/${questionId}`);
  } 
  else if (questionType === 1) {
    router.push(`/question/multiple/edit/${questionId}`);
  }
  else if (questionType === 2) {
    router.push(`/question/judge/edit/${questionId}`);
  }
  else if (questionType === 3) {
    router.push(`/question/fill/edit/${questionId}`);
  }
  else if (questionType === 4) {
    router.push(`/question/short/edit/${questionId}`);
  }
  else {
    router.push(`/question/edit/${questionId}`);
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const questionIds = row.questionId || ids.value;
  proxy.$modal.confirm('是否确认删除选中的数据项？').then(function() {
    return delQuestion(questionIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/question/export', {
    ...queryParams.value
  }, `question_${new Date().getTime()}.xlsx`)
}

// 页面加载时获取数据
onMounted(() => {
  getList();
  getChapterTreeselect();
});

//判断题答案显示
function formatJudgeAnswer(answer) {
  const mapping = {
    'A': '正确',
    'B': '错误'
  };
  return mapping[answer] || answer;
}
</script>

<style scoped>
.content-cell {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: normal;
  word-break: break-word;
  line-height: 1.5;
  max-height: 60px;
}

.answer-cell {
  cursor: pointer;
  user-select: none;
  padding: 2px 5px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.answer-hidden {
  filter: blur(4px);
}

.answer-hidden:hover {
  filter: blur(2px);
}

.score-tag {
  display: inline-block;
  padding: 2px 6px;
  background-color: #ecf5ff;
  border: 1px solid #409eff;
  border-radius: 4px;
  color: #409eff;
  font-weight: bold;
  font-size: 12px;
}

:deep(.el-tag) {
  margin-right: 5px;
}

:deep(.el-rate) {
  display: inline-block;
}

:deep(.el-tree-select) {
  width: 300px;
}

/* KaTeX 相关样式 */
:deep(.katex) {
  font-size: 1.1em;
}

:deep(.katex-display) {
  margin: 1em 0;
  overflow-x: auto;
  overflow-y: hidden;
}

:deep(.katex-html) {
  max-width: 100%;
  overflow-x: auto;
  overflow-y: hidden;
}

.blank-answer-item {
  margin-bottom: 8px;
  padding: 4px 0;
  border-bottom: 1px dashed #eee;
}

.blank-answer-item:last-child {
  border-bottom: none;
}

.answer-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
}

.answer-hidden {
  filter: blur(4px);
}

.answer-hidden:hover {
  filter: blur(2px);
}

/* 添加过渡效果 */
.answer-cell, .blank-answer-item span {
  transition: filter 0.3s ease;
}

/* 缩略图样式 */
.thumbnail-preview {
  margin-top: 5px;
  text-align: center;
}

.thumbnail-preview img {
  max-width: 100%;
  max-height: 40px;
  object-fit: contain;
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 2px;
  margin: 0 auto;
}

/* 确保图片在弹出窗口中显示正确 */
:deep(.el-popover) img {
  max-width: 100%;
  height: auto;
}

/* 预览对话框样式 */
.preview-container {
  padding: 15px;
}

.preview-type {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  gap: 10px;
}

.preview-difficulty {
  margin-left: auto;
  margin-top: 16px; /* 微调垂直偏移 */
}

.preview-score {
  background-color: #ecf5ff;
  border: 1px solid #409eff;
  border-radius: 4px;
  color: #409eff;
  font-weight: bold;
  font-size: 12px;
  padding: 3px 8px;
}

.preview-title {
  font-weight: bold;
  margin-top: 15px;
  margin-bottom: 5px;
}

.preview-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 15px;
}

.preview-option {
  display: flex;
  margin: 10px 0;
}

.option-label {
  width: 30px;
  text-align: center;
  font-weight: bold;
}

.preview-option-content {
  margin-left: 10px;
  flex: 1;
}

.preview-answer {
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
  font-weight: bold;
  color: #67c23a;
  margin-bottom: 15px;
}

.preview-blank {
  margin: 10px 0;
  padding: 10px;
  background-color: #f0f9eb;
  border-radius: 4px;
}

.preview-blank-label {
  font-weight: bold;
  margin-bottom: 5px;
}

.preview-blank-answers {
  color: #67c23a;
  font-weight: bold;
}
</style>